import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import Components from 'unplugin-vue-components/vite'
import { VantResolver } from 'unplugin-vue-components/resolvers'

export default ({ mode }) => {
  // 加载环境变量（必须在最顶层调用）
  const env = loadEnv(mode, process.cwd())

  return defineConfig({
    server: {
      proxy: {
        '/api': {
          target: 'http://localhost:8080', // 后端地址
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      }
    },
    plugins: [
      vue(),
      Components({
        resolvers: [VantResolver()],
        dts: true // 生成类型声明文件
      })
    ],
    define: {
      'process.env': {
        VITE_API_BASE_URL: JSON.stringify(env.VITE_API_BASE_URL)
      }
    },
    resolve: {
      alias: {
        "@": resolve(__dirname, "src")
      }
    },
    build: {
      rollupOptions: {
        output: {
          manualChunks: {
            vant: ['vant'],
            vue: ['vue', 'vue-router']
          }
        }
      }
    }
  })
}